#include "Logic.h"

Logic* Logic::_oneLogic = NULL;

Logic* Logic::getInstance() {
	if( _oneLogic == NULL ) {
		_oneLogic = new Logic();
		_oneLogic->setupParser();
	}

	return _oneLogic;
}

Display Logic::executeUserCommand( string userCommand ) {
	_commandBase = _parser->parseUserCommand( userCommand );

	if (_commandBase != NULL) {
		_commandBase->execute();
		_display = LogicBase::getDisplay();
	}else {
		vector<Task> view;
		view = _display.getTaskList();
		_display = Display(INVALID_COMMAND_MESSAGE, view );
	}

	return _display;
}

void Logic::setupParser() {
	_parser = new Parser();
}

void Logic::setupData() {
	_data = new Data();
}

void Logic::setupWriter() {
	_writer = new Writer(FILE_NAME);
}


// read and store in Data
void Logic::populateData() {
	vector<Task> initVector;

	_writer->read(initVector);
	_data->executeLoad(initVector);
}

// sets up the program before user begins using it
// populates the internal vector with tasks from files
Logic::Logic() {
	setupParser();
	setupData();
	setupWriter();
	populateData();
	LogicBase::initialize(_data, _writer);
}

Logic::~Logic() {
	delete _parser;
	delete _data;
	delete _writer;
}

void Logic::logErrors( string errorMessage )
{
	fstream log;
	log.open(ERROR_LOG_FILE_NAME, fstream::in | fstream::app);

	log << errorMessage << endl;

	log.close();
}

// status messages
const string Logic::INVALID_COMMAND_MESSAGE = "Invalid Command";

// main file name
const string Logic::FILE_NAME = "schedulerPP.txt";
const string Logic::ERROR_LOG_FILE_EOF = "========END========";

// error log file name
const string Logic::ERROR_LOG_FILE_NAME = "log.txt";